package cn.com.bsoft.cloud

import cn.net.xyan.blossom.kotlin.AllOpen
import org.springframework.context.annotation.Configuration
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import javax.sql.DataSource
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.transaction.PlatformTransactionManager
import org.mybatis.spring.SqlSessionFactoryBean
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.annotation.MapperScan
import org.springframework.context.annotation.Primary


@Configuration
@AllOpen
@MapperScan(basePackages = arrayOf("cn.com.bsoft.cloud.dao.cloud"),
        annotationClass = UseDatasourceCloud::class,
        sqlSessionFactoryRef = CloudConfiguration.SQL_SESSION_FACTORY_NAME)
class CloudConfiguration{

    companion object {
        const val TX_MANAGER = "txManagerCloud"
        const val SQL_SESSION_FACTORY_NAME = "sessionFactoryCloud"
    }

    @Primary
    @Bean(name = arrayOf("datasourceCloud"))
    @ConfigurationProperties(prefix = "datasource.cloud")
    fun datasourceCloud(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Primary
    @Bean(name = arrayOf(TX_MANAGER))
    fun txManager(): PlatformTransactionManager {
        return DataSourceTransactionManager(datasourceCloud())
    }

    @Primary
    @Bean(name = arrayOf(SQL_SESSION_FACTORY_NAME))
    @Throws(Exception::class)
    fun sqlSessionFactoryBean(): SqlSessionFactory {

        val sqlSessionFactoryBean = SqlSessionFactoryBean()
        //sqlSessionFactoryBean.setConfigLocation(ClassPathResource("/mybatis/healthweb/mybatis-conf.xml"))
        sqlSessionFactoryBean.setDataSource(datasourceCloud())
       // sqlSessionFactoryBean.setTypeAliasesPackage("cn.com.bsoft.immunity.entity.healthweb")
       // sqlSessionFactoryBean.setMapperLocations(PathMatchingResourcePatternResolver().getResources("/mybatis/healthweb/*Mapper.xml"))
        return sqlSessionFactoryBean.`object`
    }
}